import time
from datetime import datetime, timedelta

from flask import render_template, request, session, redirect, url_for, g, current_app, jsonify

from info import constants, db
from info.models import User, News, Category
from info.modules.admin import admin_blu
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET


@admin_blu.route('/news_type', methods=['GET', 'POST'])
def news_type():
    if request.method == 'GET':
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.NODATA, errmsg="数据库查询失败")

        category_dict_li = []
        for category in categories:
            cate_dict = category.to_dict()
            category_dict_li.append(cate_dict)
        category_dict_li.pop(0)

        data = {'categories': category_dict_li}

        return render_template('admin/news_type.html', data=data)
    # post 请求
    category_id=request.json.get('id')
    category_name=request.json.get('name')
    if not category_name:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if category_id:
        try:
            category_id=int(category_id)
            categories=Category.query.get(category_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
        if not categories:
            return jsonify(errno=RET.NODATA, errmsg="数据库查询失败")
        categories.name=category_name
    else:
        category=Category()
        category.name=category_name
        db.session.add(category)

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")

    return jsonify(errno=RET.OK, errmsg="OK")


@admin_blu.route('/news_edit_detail', methods=['GET', 'POST'])
def news_edit_detail():
    """新闻编辑详情页"""
    if request.method == 'GET':
        news_id = request.args.get('news_id')
        if not news_id:
            return render_template('admin/news_edit_detail.html', data={'errmsg': '未查询到此新闻'})

        news = None
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)

        if not news:
            return render_template('admin/news_edit_detail.html', data={'errmsg': '未查询到此新闻'})
        # 查询分类数据
        categories = Category.query.all()
        categories_li = []
        for category in categories:
            c_dict = category.to_dict()
            c_dict['is_selected'] = False
            if category.id == news.category_id:
                c_dict['is_selected'] = True
            categories_li.append(c_dict)

        data = {'news': news, 'categories': categories_li}
        return render_template('admin/news_edit_detail.html', data=data)
    # post请求
    # 获取参数
    news_id = request.form.get('news_id')
    title = request.form.get('title')
    index_image_url = request.files.get('index_image')
    digest = request.form.get('digest')
    content = request.form.get('content')
    category_id = request.form.get('category_id')
    # 校验参数
    if not all([news_id, title, digest, content, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        news_id = int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)

    if not news:
        return render_template('admin/news_review_detail.html', data={'errmsg': '未查询到此新闻'})
        # 读取图片
    if index_image_url:
        try:
            image_url = index_image_url.read()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
        # 图片上传到七牛云
        try:
            image_url = storage(image_url)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg='图片上传失败')
        news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_url

    # 更改数据库数据

    news.title = title
    news.category_id = category_id
    news.digest = digest

    news.content = content

    # 将数据保存到数据库
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='数据保存失败')
    return jsonify(errno=RET.OK, errmsg='新闻发布成功，待审核')

    # 更改数据库


@admin_blu.route('/news_edit')
def news_edit():
    """新闻编辑"""
    # 获取参数
    page = request.args.get('p', 1)
    keywords = request.args.get('keywords', "")
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)

    # 查询数据库
    news = []
    current_page = 1
    total_page = 1
    try:
        filters = [News.status == 0]
        # 如果有关键字
        if keywords:
            # 添加关键字的检索选项
            filters.append(News.title.contains(keywords))
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,
                                                                                          constants.ADMIN_USER_PAGE_MAX_COUNT,
                                                                                          False)
        news = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
    # 将模型列表转换为字典
    news_list = []
    for new in news:
        news_list.append(new.to_basic_dict())
        data = {
            "current_page": current_page,
            "total_page": total_page,
            "news_list": news_list
        }

    return render_template('admin/news_edit.html', data=data)


@admin_blu.route('/news_review_detail/<int:news_id>', methods=['POST', 'GET'])
def news_review_detail(news_id):
    """新闻审核具体实现"""
    if request.method == 'GET':
        if not news_id:
            return render_template('admin/news_review_detail.html', data={'errmsg': '未查询到此新闻'})

        news = None
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)

        if not news:
            return render_template('admin/news_review_detail.html', data={'errmsg': '未查询到此新闻'})
        data = {'news': news.to_dict()}
        print(data)
        return render_template('admin/news_review_detail.html', data=data)
    # 执行审核操作
    # 获取参数
    news_id = request.json.get('news_id')
    action = request.json.get('action')
    # 校验参数
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if action not in ("accept", "reject"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 查询新闻
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="未查询到数据")
    # 根据不同的状态设置不同的值
    if action == 'accept':
        # 已通过
        news.status = 0
    else:
        # 未通过
        reason = request.json.get('reason')
        if not reason:
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
        news.reason = reason
        news.status = -1

    # 保存到数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DATAERR, errmsg='数据保存失败')
    return jsonify(errno=RET.OK, errmsg='ok')


@admin_blu.route('/news_review')
def news_review():
    """新闻审核"""
    # 获取参数
    page = request.args.get('p', 1)
    keywords = request.args.get('keywords', "")
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)

    # 查询数据库
    news = []
    current_page = 1
    total_page = 1
    try:
        filters = [News.status != 0]
        # 如果有关键字
        if keywords:
            # 添加关键字的检索选项
            filters.append(News.title.contains(keywords))
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,
                                                                                          constants.ADMIN_USER_PAGE_MAX_COUNT,
                                                                                          False)
        news = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
    # 将模型列表转换为字典
    news_list = []
    for new in news:
        news_list.append(new.to_review_dict())
    data = {
        "current_page": current_page,
        "total_page": total_page,
        "news_list": news_list
    }

    return render_template('admin/news_review.html', data=data)


@admin_blu.route('/user_list')
def user_list():
    """用户列表"""
    # 获取参数
    page = request.args.get('p', 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)

    # 查询数据库
    users = []
    current_page = 1
    total_page = 1
    try:
        paginate = User.query.filter(User.is_admin == False).order_by(User.last_login.desc()).paginate(page,
                                                                                                       constants.ADMIN_USER_PAGE_MAX_COUNT,
                                                                                                       False)
        users = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
    # 将模型列表转换为字典
    users_list = []
    for user in users:
        users_list.append(user.to_admin_dict())
        data = {
            "current_page": current_page,
            "total_page": total_page,
            "user_info": users_list
        }

    return render_template('admin/user_list.html', data=data)


@admin_blu.route('/user_count')
def user_count():
    """查询总人数
    查询月新增人数
    查询日新增人数
    查询图表信息"""
    # 查询总人数
    total_count = 0
    try:
        total_count = User.query.filter(User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)

    # 查询月新增人数
    mon_count = 0
    try:
        now = time.localtime()
        mon_begin = '%d-%2d-01' % (now.tm_year, now.tm_mon)
        mon_begin_date = datetime.strptime(mon_begin, '%Y-%m-%d')
        mon_count = User.query.filter(User.is_admin == False, User.create_time > mon_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)
    # 查询日新增人数
    day_count = 0
    try:
        now = time.localtime()
        day_begin = '%d-%2d-%2d' % (now.tm_year, now.tm_mon, now.tm_mday)
        day_begin_date = datetime.strptime(day_begin, '%Y-%m-%d')
        day_count = User.query.filter(User.is_admin == False, User.create_time > day_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 查询图表信息

    now_data = datetime.strptime(datetime.now().strftime('%Y-%m-%d'), '%Y-%m-%d')
    # 定义空数组，保存数据
    active_date = []
    active_count = []

    for i in range(0, 31):
        begin_date = now_data - timedelta(days=i)
        end_date = now_data - timedelta(days=(i - 1))
        active_date.append(begin_date.strftime('%Y-%m-%d'))
        count = 0
        try:
            count = User.query.filter(User.is_admin == False, User.last_login >= begin_date,
                                      User.last_login <= end_date).count()
        except Exception as e:
            current_app.logger.error(e)
        active_count.append(count)

    active_date.reverse()
    active_count.reverse()
    data = {
        "total_count": total_count,
        "mon_count": mon_count,
        "day_count": day_count,
        "active_date": active_date,
        "active_count": active_count
    }

    return render_template('admin/user_count.html', data=data)


@admin_blu.route('/index')
@user_login_data
def admin_index():
    """管理员主页"""
    user = g.user
    data = {
        'user_info': user.to_dict()
    }
    return render_template('admin/index.html', data=data)


@admin_blu.route('/login', methods=['GET', 'POST'])
def admin_login():
    """管理员登录页面"""
    if request.method == 'GET':
        # 如果用户已经登录，那么直接重定向到管理员主页
        user_id = session.get('user_id', None)
        is_admin = session.get('is_admin', False)
        if user_id and is_admin:
            return redirect(url_for('admin.admin_index'))
        return render_template('admin/login.html')

    username = request.form.get('username')
    password = request.form.get('password')
    if not all([username, password]):
        return render_template('admin/login.html', errmsg='参数错误')
    try:
        user = User.query.filter(User.mobile == username, User.is_admin == True).first()
    except Exception as e:
        return render_template('admin/login.html', errmsg='用户信息查询失败')
    if not user:
        return render_template('admin/login.html', errmsg='未查询到用户信息')
    if not user.check_passowrd(password):
        return render_template('admin/login.html', errmsg='用户名或密码错误')
    session['user_id'] = user.id
    session['mobile'] = user.mobile
    session['nick_name'] = user.nick_name
    session['is_admin'] = user.is_admin

    # 跳转到管理员主页
    return redirect(url_for('admin.admin_index'))
